package dao

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
)

type User struct {
	Avatar          string `json:"avatar"`           // 用户头像
	BackgroundImage string `json:"background_image"` // 用户个人页顶部大图
	FavoriteCount   int64  `json:"favorite_count"`   // 喜欢数
	FollowCount     int64  `json:"follow_count"`     // 关注总数
	FollowerCount   int64  `json:"follower_count"`   // 粉丝总数
	ID              int64  `json:"id"`               // 用户id
	IsFollow        bool   `json:"is_follow"`        // true-已关注，false-未关注
	Name            string `json:"name"`             // 用户名称
	Signature       string `json:"signature"`        // 个人简介
	TotalFavorited  string `json:"total_favorited"`  // 获赞数量
	WorkCount       int64  `json:"work_count"`       // 作品数
}

type Account struct {
	UserInfo User   `gorm:"embedded"`
	Password string `json:"password"`
}

type UserDao struct{}

func QueryUserByName(username string) (*User, error) {
	var acc Account
	var err error
	err = db.Table("UserInfo").Where("name = ?", username).First(&acc).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		fmt.Println("Can't find!!!")
		return nil, nil
	}
	if err != nil {
		fmt.Println("OOPS!!!")
		return nil, err
	}
	return &acc.UserInfo, nil
}

func AddUser(username string, password string) int64 {
	var user User = User{Name: username}
	var acc Account = Account{user, password}
	db.Table("UserInfo").Create(&acc)
	id := acc.UserInfo.ID

	return id
}

func Login(username string, password string) (int64, error) {
	var acc Account
	err := db.Table("userinfo").Where("name = ?", username).First(&acc).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return -1, err
	} else if err == nil && password == acc.Password {
		return acc.UserInfo.ID, nil
	}
	return -1, err
}
